<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once 'classes/notesClass.php';

/**
 * Description of common
 *
 * @author nstevens
 */
class commonModel {

    //put your code here
    public $title, $startDate, $endDate, $wbsID, $wbsString, $ID, $status, $string;
    public $approvedCost, $proposedCost, $actualCost, $notes;

    //HTML**********************************************************************

    public function getEditProfilePage() {
        $person = new projectPersonnel(NULL, getCurrentUser());
        $output = "";
        $output .= $this->getBasicHeader("Edit Profile");
        if (isset($_GET['update'])) {
            $output .= $this->getFlagUnorderedList($_GET['update']);
        }
        $output .= getFormLinePost("editProfileForm", "mainPage.php?request=common&action=processEditProfileRequest");
        $output .= '<table class="width40Center" cellspacing="1">';
        $output .= '<caption>Edit Profile</caption>';
        $output .= '<tr>';
        $output .= $this->getTD('Username', "header");
        $output .= $this->getTD(getCurrentUser() . getHiddenField("personID", $person->personID), "field");
        $output .= '<tr>';
        $output .= '<tr>';
        $output .= $this->getTD('Role', "header");
        $output .= $this->getTD($person->role, "field");
        $output .= '<tr>';
        $output .= '<tr>';
        $output .= $this->getTD('Name', "header");
        $output .= $this->getTD(getFormInputElement('text', 'name', '97%', $person->name), "field");
        $output .= '<tr>';
        $output .= '<tr>';
        $output .= $this->getTD('Email', "header");
        $output .= $this->getTD(getFormInputElement('text', 'email', '97%', $person->email), "field");
        $output .= '<tr>';
        $output .= '<tr>';
        $output .= $this->getTD('Phone', "header");
        $output .= $this->getTD(getFormInputElement('text', 'phone', '97%', $person->phone), "field");
        $output .= '<tr>';
        $output .= '<tr>';
        $output .= $this->getTD('Company', "header");
        $output .= $this->getTD(getFormInputElement('text', 'company', '97%', $person->company), "field");
        $output .= '<tr>';
        $output .= '<tr>';
        $output .= $this->getTD('Address', "header");
        $output .= $this->getTD(getFormInputElement('text', 'address', '97%', $person->address), "field");
        $output .= '<tr>';
        $output .= '<tr>';
        $output .= $this->getTD("", "header");
        $output .= $this->getTD(getFormInputElement('submit', 'submit', '50%', "Save Profile"), "field");
        $output .= '<tr>';
        $output .= '</table></form></body></html>';
        return $output;
    }

    public function processEditProfile() {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $company = $_POST['company'];
        $address = $_POST['address'];
        $personID = $_POST['personID'];
        $result = executeUpdate("UPDATE person SET name='$name', email='$email', phone='$phone', 
                                 company='$company', address='$address' WHERE personID=$personID");
        if ($result) {
            return 'location:mainPage.php?request=common&action=editProfileRequest&update=Succcessfully updated profile';
        } else {
            return NULL;
        }
    }

    /**
     * Gets the header all the way after the menu bar
     * @param type $title
     * @param type $useDatepicker
     * @param type $showLogo
     * @param type $start
     * @param type $end
     * @return string
     */
    public function getBasicHeader($title, $useDatepicker = NULL, $showLogo = NULL, $start = NULL, $end = NULL) {
        $output = "";
        $output .= getNewHtmlUpToMeta();
        //CSS
        foreach (getAllCSSFileArray() as $file) {
            $output .= getCSSFileLine($file);
        }
        //js
        foreach (getAllJSFileArray() as $file) {
            $output .= getJavascriptFileLine($file);
        }
        if ($useDatepicker) {
            $output .= getDatepickerStuff();
        }

        if ($start) {
            $output .= getSubtaskDatepicker($start, $end, true, true);
        }
        $output .= getExpandCollapseAllScript();
        //$output .= getExpandOneCollapseOneScript();
        $output .= getConfirmBoxScript();
        $output .= getTitle($title);
        $output .= getCloseTag("head");
        $output .= getOpenTag("body");
        if ($showLogo) {
            $output .= getLogoLine();
        }
        $output .= getLoggedInAsLine();
        $output .= getMenuBar(getUserRole());
        $output .= '<br>';
        $output .= '<br>';
        return $output;
    }

    /*
     * Gets the Required text for required fields in a form
     */

    static function getRequiredFieldText() {
        return '<span class="required">* required field</span>';
    }

    /**
     * Gets red text for given input
     * @param type $text text you wish to display
     * @return type
     */
    public function getRedText($text) {
        return "<span class=\"required\">* $text</span>";
    }

    public function getHelpPage() {
        $output = "";
        $output .= $this->getBasicHeader("Help Page");
        $output .= "<h2>User Guide: <a href='userGuide.doc'>Download</a> (need to upload user guide when it is complete)</h2>";
        $output .= "<h2>Proposal Flow Chart</h2>";
        $output .= '<img border="0" src="images/proposalFlowDiagram.png" width="1000" height="700">';
        return $output;
    }

    /**
     * Returns the html form for a simple FY dropdown and submit button (starting with current fy out 6 years)
     * @param type $formAction
     * @param type $buttonText
     * @param type $caption
     * @param type $dropdownAction
     * @param type $allProjects if true then returns all fy that contain at least 1 project
     */
    function getFiscalYearSubmitForm($formAction, $buttonText, $caption = NULL, $dropdownAction = NULL, $allProjects = NULL) {
        $output = "";
        $output .= '<div class="centered">';
        $output .= getFormLinePostWithOnSubmit("fySubmitForm", $formAction, "validateFYForm(this)");
        $output .= '<table class="width20Center" cellspacing="1">';
        if ($caption) {
            $output .= '<caption>' . $caption . '</caption>';
        } else {
            $output .= '<caption>Select Fiscal Year</caption>';
        }
        $output .= ' <tr class ="fieldLabel"><td class="center">Execution FY</td><tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td class="center">';
        if ($allProjects) {
            if ($dropdownAction) {
                $output .= getDropDownMenu(getProjectFiscalYearArray(), "fyDropdown", NULL, NULL, $dropdownAction, "fyDropdown");
            } else {
                $output .= getDropDownMenu(getProjectFiscalYearArray(), "fyDropdown", NULL, NULL, NULL, "fyDropdown");
            }
        } else if ($dropdownAction) {
            $output .= getDropDownMenu(getFiscalYearArray(), "fyDropdown", NULL, NULL, $dropdownAction, "fyDropdown");
        } else {
            $output .= getDropDownMenu(getFiscalYearArray(), "fyDropdown", NULL, NULL, NULL, "fyDropdown");
        }
        $output .= '     </td>';
        $output .= ' </tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td class="center">';
        $output .= getFormInputElement("submit", "submit", NULL, $buttonText);
        $output .= '     </td>';
        $output .= ' </tr>';
        $output .= getCloseTag("table");
        $output .= getCloseTag("form");
        $output .= getCloseTag("div");
        return $output;
    }

    /**
     * Returns a notes form populating data from the passed in array
     * @param type $notesObjectArray
     * @param type $action
     * @param type $caption
     * @param type $showLink
     * @return type
     */
    function getNotesFormFromObject($notesObjectArray, $action = NULL, $caption = NULL, $showLink = NULL) {

        //do not let PIs see reviewer notes
        if ($caption && strcmp($caption, "Reviewer Notes") === 0 && strcmp(getUserRole(), "pi") === 0) {
            return;
        }
        $output = "";
        if ($action) {
            $output .= getFormLinePost("feedbackForm", $action);
        } else {
            $output .= getFormLinePost("feedbackForm", "mainPage.php?request=notes&action=processExistingNotesRequest");
        }
        if ($caption) {
            $caption = "<caption>$caption</caption>";
        } else {
            $caption = "Feedback";
            $caption = "<caption>$caption</caption>";
        }
        $output .= '<table class="width100" cellspacing="1">';
        $output .= '<col width="45%"><col width="12%"><col width="9%"><col width="9%"><col width="9%">';
        $output .= $caption;
        $output .= ' <tr class ="header">';
        $output .= '     <td>Comments</td>';
        $output .= '     <td>Person</td>';
        $output .= '     <td>Date Created</td>';
        $output .= '     <td>Last Updated</td>';
        $output .= '     <td>Status</td>';
        $output .= '     <td>Options</td>';
        $output .= ' </tr>';
        $counter = 0;
        foreach ($notesObjectArray as $note) {
            $output .= '<tr class="field">';


            $curPersonID = getPersonIDFromUsername(getCurrentUser());
            //if this is the user that created the notes allow them to modify them
            if ($curPersonID == $note->personId) {
                $output .= "<td>";
                $output .= getFormInputElement('text', "textFieldNotes$counter", '97%', $note->notes);
                $output .= getHiddenField("notesID$counter", $note->ID);
                $output .= "</td>";
            }
            //just show the text
            else {
                if ($showLink) {
                    $output .= '<td><a href="' . $note->urlLink . '" class="black">';
                    $output .= "$note->notes ($note->wbsString)</a></td>";
                } else {
                    $output .= "<td>$note->notes</td>";
                }
            }

            $output .= "<td>$note->name</td>";
            $output .= '<td>' . $note->dateCreated . '</td>';
            $output .= '<td>' . $note->lastUpdated . '</td>';
            $output .= '<td>' . $note->status . '</td>';
            $output .= '<td>';
            $output .= $this->getNotesFormOptionButton($note, $counter, $note);
            $output .= getHiddenField('notes' . $counter . '', $note->notes);
            $output .= getHiddenField('wbs' . $counter . '', $note->wbsId);
            $output .= '</td>';
            $output .= '</tr>';
            $counter++;
            // }
        }
        $output .= getCloseTag("table");
        $output .= getCloseTag("form");
        return $output;
    }

    /**
     * Returns buttons depending on the status
     * @param type $status
     * @param type $counter
     * @param type $personID
     * @return type
     */
    function getNotesFormOptionButton($note, $counter) {
        $status = $note->status;
        $personID = $note->personId;
        $type = $note->type;
        $output = "";
        //if this person created the note let them edit it
        $curPersonID = getPersonIDFromUsername(getCurrentUser());
        if ($curPersonID == $personID) {
            $buttonName = 'button' . $counter . '';
            $output .= getFormInputElement('submit', $buttonName, "100%", "Update Notes");
        } else if (strcmp($status, "created") === 0 && strcmp(getUserRole(), "pi") === 0) {
            $buttonName = 'button' . $counter . '';
            $output .= getFormInputElement('submit', $buttonName, "100%", "Mark as complete");
        }
        return $output;
    }

    /**
     * Returns the legend for the financials table
     * @return string
     */
    function getStatusColorLegendTable() {
        $output = "";
        $output .= '<table class="width100" cellspacing="1">';
        $output .= '<td bgcolor = "' . getStatusBackgroundColor("started", "task") . '">started</td>';
        $output .= '<td bgcolor = "' . getStatusBackgroundColor("notStarted", "task") . '">not started</td>';
        $output .= '<td bgcolor = "' . getStatusBackgroundColor("pending", "task") . '">pending</td>';
        $output .= '<td bgcolor = "' . getStatusBackgroundColor("completed", "task") . '">completed</td>';
        $output .= '</table>';
        return $output;
    }

    /**
     * Is the current status of the object calling this function equal to the passed in status
     * @param type $status status to compare to
     * @return boolean match=true, different=false
     */
    function isStatus($status) {
        if (strcmp($status, $this->status) === 0)
            return true;
        else
            return false;
    }

    /**
     * Returns a single entry to display at the top of a page if an event occurred
     * @param type $text
     * @return type
     */
    static function getFlagUnorderedList($text) {
        return '<ul id="ulist"><li class="green">' . $text . '</li></ul>';
    }

    function getUnorderedList($text) {
        return '<ul id="ulist"><li>' . $text . '</li></ul>';
    }

    /**
     * 
     * @param type $text
     * @param type $class
     * @param type $id
     * @param type $options
     * @return type
     */
    static function getTD($text = NULL, $class = NULL, $id = NULL, $options = NULL) {
        if ($class) {
            $class = "class='$class'";
        }
        if ($id) {
            $id = "id='$id'";
        }
        return "<td $class $id $options>$text</td>";
    }

    //FILL DATA*****************************************************************
    /**
     * Pulls notes from the db for the given type and wbsID
     * @param type $type
     * @return array
     */
    function getNotesFromDB($type) {
        $array = array();
        $notesResult = executeSelect("SELECT * from notes where wbsId=$this->wbsID AND type='$type' ");
        while ($row = mysqli_fetch_array($notesResult)) {
            $notesObj = new notesClass($row);
            array_push($array, $notesObj);
        }
        return $array;
    }

    /**
     * Retrieves the notes of a given type from the notes array (if null pulls them from the db)
     * @param type $type
     * @param type $subtype
     * @param type $value must have a subtype if requesting a value match
     * @return array
     */
    function getNotes($type, $subtype = NULL, $value = NULL) {
        $array = array();
        if (!$this->notes) {
            $this->notes = $this->getAllNotes();
        }
        foreach ($this->notes as $note) {
            if (strcmp($note->type, $type) === 0) {
                if ($subtype) {
                    if (strcmp($note->subType, $subtype) === 0) {
                        if ($value) {
                            if (strcmp($note->value, $value) === 0) {
                                array_push($array, $note);
                            }
                        } else {
                            //echo "Push -> type: $type sub: $subtype <br>";
                            array_push($array, $note);
                        }
                    }
                }
                else
                    array_push($array, $note);
            }
        }
        //echo sizeof($array);
        return $array;
    }

    /**
     * Gets the local notes array
     * @return type
     */
    function getNotesArray() {
        if (!$this->notes) {
            return $this->getAllNotes();
        } else {
            return $this->notes;
        }
    }

    /**
     * Pulls all notes from the DB given the wbsID
     * @return array
     */
    function getAllNotes() {
        $array = array();
        $notesResult = executeSelect("SELECT * from notes where wbsId=$this->wbsID");
        while ($row = mysqli_fetch_array($notesResult)) {
            $notesObj = new notesClass($row);
            array_push($array, $notesObj);
        }
        return $array;
    }

    //TASK (PRODUCT/CAPABILITY) STUFF*******************************************
    /**
     * Builds a form to submit a new or edit an existing task
     * @param type $taskObject if NULL --> returns an empty form, 
     * else --> returns a form with populated fields (edit existing task)
     * @return type the form
     */
    static function getTaskForm($taskObject = NULL) {
        $output = "";
        if (!$taskObject) {
            $projectID = $_GET['projectID'];
            $output .= getFormLinePostWithOnSubmit("createTaskForm", " mainPage.php?request=common&action=processTaskSubmitRequest&projectId=$projectID", "validateTask(this)");
        } else {
            $output .= getFormLinePostWithOnSubmit("createTaskForm", " mainPage.php?request=common&action=processTaskSubmitRequest&taskId=$taskObject->ID&projectId=$taskObject->projectID", "validateTask(this)");
        }
        $output .= '<table class="width100" cellspacing="1">';
        $output .= '<caption>New Task</caption>';
        $output .= ' <tr class ="header"><td  colspan="2">Title</td></tr>';
        $output .= ' <tr class="field"><td  colspan="2">';
        if (!$taskObject) {
            $output .= getFormInputElement("text", 'titleTextfield', '99%');
        } else {
            $output .= getFormInputElement("text", 'titleTextfield', '99%', $taskObject->title);
        }
        $output .= '     </td>';
        $output .= ' <tr class ="header"><td  colspan="2">Description</td></tr>';
        $output .= ' <tr class="field"><td  colspan="2">';
        if (!$taskObject) {
            $output .= getTextArea('descriptionTextfield', 1000);
        } else {
            $output .= getTextArea('descriptionTextfield', 1000, $taskObject->description);
        }
        $output .= '     </td>';
        $output .= ' </tr>';

        //req and params (comment if we do not want this)
        $output .= commonModel::getParamCheckboxes($taskObject);
        $output .= commonModel::getReqCheckboxes($taskObject);

        $output .= ' <tr class ="fieldLabel"><td>';
        if (!$taskObject) {
            $output .= getFormInputElement("submit", "submit", NULL, "Create Task");
        } else {
            $output .= getFormInputElement("submit", "submit", NULL, "Save Task");
        }
        $output .= '     </td>';
        if (!$taskObject) {
            $output .= '     <td><input type="hidden" name="projectId" value="' . $projectID . '">';
        } else {
            $output .= '     <td><input type="hidden" name="projectId" value="' . $taskObject->projectID . '">';
        }
        if (!$taskObject) {
            $output .= getHiddenField("submissionType", 'create');
        } else {
            $output .= getHiddenField("submissionType", 'edit');
        }
        if ($taskObject) {
            $output .= getHiddenField("taskId", $taskObject->ID);
        }
        $output .= '     </td>';
        $output .= ' </tr>';
        $output .= getCloseTag("table");
        $output .= getCloseTag("form");
        return $output;
    }

    /**
     * Gets a checkbox list of all parameters 
     * @param type $taskObject if NULL --> returns all unchecked, 
     * else --> returns checked fields (edit existing task)
     * @return string a tr with the checkbox list inside
     */
    static function getParamCheckboxes($taskObject) {
        $output = "";
        //parameter title row 
        $output .= '<tr class ="header"><td colspan="3">Select applicable parameter(s)</td></tr>';
        //parameters data row
        $output .= '<tr>';
        $output .= ' <td colspan="3" class="col-2">
                       <div class="container1200px">';
        $counter = 0;
        $paramResult = executeSelect("SELECT * FROM parameter");
        while ($row = mysqli_fetch_array($paramResult)) {
            $parameterID = $row['parameterID'];
            $name = $row['name'];
            if ($taskObject && isSringInArray($parameterID, $taskObject->parameters)) {
                $output .= "<input name =\"paramCheckbox$counter\" id =\"paramCheckbox$counter\" value = \"$parameterID\"type=\"checkbox\"/ checked>$name<br />";
            } else {
                $output .= "<input name =\"paramCheckbox$counter\" id =\"paramCheckbox$counter\" value = \"$parameterID\"type=\"checkbox\"/>$name<br />";
            }
            $counter++;
        }
        $output .= ' </div></td></tr>';
        return $output;
    }

    /**
     * Gets a checkbox list of all requirements 
     * @param type $taskObject if NULL --> returns all unchecked, 
     * else --> returns checked fields (edit existing task)
     * @return string a tr with the checkbox list inside
     */
    static function getReqCheckboxes($taskObject) {
        $output = "";
        //req title row 
        $output .= '<tr class ="header"><td colspan="3">Select applicable OPNAV Guidance Letter Prioritized Requirements</td></tr>';
        //req data row
        $output .= '<tr>';
        $output .= '<td colspan="3" class="col-2"><div class="container1200px">';
        $counter = 0;
        $reqResult = executeSelect("SELECT * FROM requirement ORDER by priority");
        while ($row = mysqli_fetch_array($reqResult)) {
            $reqID = $row['reqID'];
            $name = $row['description'];
            $priority = $row['priority'];
            if ($taskObject && isSringInArray($reqID, $taskObject->requirements)) {
                $output .= "<input name =\"reqCheckbox$counter\" id =\"reqCheckbox$counter\" value = \"$reqID\"type=\"checkbox\" checked/>$name ($priority)<br />";
            } else {
                $output .= "<input name =\"reqCheckbox$counter\" id =\"reqCheckbox$counter\" value = \"$reqID\"type=\"checkbox\"/>$name ($priority)<br />";
            }
            $counter++;
        }
        $output .= ' </div></td>';
        $output .= ' </tr>';
        return $output;
    }

    //Process a new or edit an existing task
    static function processTaskSubmit() {
        $taskTitle = $_POST['titleTextfield'];
        $desc = $_POST['descriptionTextfield'];
        $projectID = $_POST['projectId'];
        $update = false;
        //existing task
        if (isset($_POST['taskId'])) {
            //update the task
            $taskID = $_POST['taskId'];
            $update = true;
            executeUpdate("UPDATE task SET title='$taskTitle', description='$desc' WHERE taskID=$taskID");
            //delete old parameters
            executeDelete("DELETE FROM taskparammap WHERE taskID=$taskID");
            //delete old requirements
            executeDelete("DELETE FROM taskreqmap WHERE taskID=$taskID");
        }
        //new task
        else {
            $wbsString = getWbsString(getFieldGivenAnID('project', 'projectID', $projectID, 'wbsId'));
            $nextWbs = getNextWbsAtThisLevel($wbsString);
            $fy = getFieldGivenAnID('project', 'projectID', $projectID, 'fy');
            $wbsID = executeInsert("INSERT into wbs (wbsString, description, other, level, fy) values ('$nextWbs', '$taskTitle','$desc',2, $fy)");
            $sqlInsert = "INSERT into task (projectID,title,description,wbsID,status) VALUES ($projectID,'$taskTitle','$desc','$wbsID','subtaskRequired')";
            $taskID = executeInsert($sqlInsert);
        }

        $relateReqAndParam = true;
        if ($relateReqAndParam) {
            $paramArray = getgenericList('paramCheckbox', 50);
            foreach ($paramArray as $paramID) {
                executeInsert("INSERT into taskparammap (taskID, paramID) values ($taskID, $paramID)");
            }
            $reqArray = getgenericList('reqCheckbox', 50);
            foreach ($reqArray as $reqID) {
                executeInsert("INSERT into taskreqmap (taskID, reqID) values ($taskID, $reqID)");
            }
        }
        projectModelClass::updateNewProjectStatusFromOldStatic($projectID);
        if ($update) {
            return "location:mainPage.php?request=task&action=viewTaskDetailsRequest&projectId=$projectID&taskId=$taskID&update=Successfully saved changes";
        } else {
            return "location:mainPage.php?request=task&action=viewTaskDetailsRequest&projectId=$projectID&taskId=$taskID&update=Create at least 1 subtask below";
        }
    }

    //SUBTASK STUFF*************************************************************
    /**
     * Gets the subtask create/edit form
     * @param type $subtaskObject if not null populates the subtask fields
     * @return type an html form as a string 
     */
    static function getSubtaskForm($subtaskObject = NULL) {
        $projectID = $_POST['projectID'];
        $taskID = $_POST['taskId'];
        $startDate = $_POST['projectStartDate'];
        $endDate = $_POST['projectEndDate'];
        $output = "";
        if ($subtaskObject) {
            $caption = '<caption>Edit Subtask</caption>';
            $output .= getFormLinePostWithOnSubmit("createTaskForm", " mainPage.php?request=common&action=processSubtaskSubmitRequest&taskId=$taskID&projectId=$projectID&subtaskId=$subtaskObject->ID", "validateTask(this)");
        } else {
            $caption = '<caption>New Subtask</caption>';
            $output .= getFormLinePostWithOnSubmit("createTaskForm", " mainPage.php?request=common&action=processSubtaskSubmitRequest&taskId=$taskID&projectId=$projectID", "validateTask(this)");
        }
        //Table Start***************************************************************
        $output .= commonModel::getRequiredFieldText();
        $colWidth = 100 / 10;
        $output .= '<table class="width100" cellspacing="1">';
        $output .= '<col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%">';
        $output .= $caption;
        $output .= ' <tr class="row-category"><td class="col-2" colspan="10">Subtask Description</td></tr>';

        //Section 1 Title, Description**********************************************
        $output .= ' <tr class ="header"><td colspan="3">Title</td><td colspan="7">Description</td></tr>';
        $output .= ' <tr class="field"><td class="required" colspan="3">';
        if ($subtaskObject)
            $output .= getFormInputElementText("text", 'titleTextField', '95%', $subtaskObject->title);
        else
            $output .= getFormInputElementText("text", 'titleTextField', '95%');
        $output .= '     *</td>';
        $output .= '     <td class="required" colspan="7">';
        if ($subtaskObject)
            $output .= getFormInputElementText("text", 'descriptionTextField', '95%', $subtaskObject->description, NULL, 'descriptionTextfield');
        else
            $output .= getFormInputElementText("text", 'descriptionTextField', '95%', NULL, NULL, 'descriptionTextfield');
        $output .= '     *</td></tr>';

        //Section 2  Category**************************
        $output .= ' <tr class ="header"><td colspan="3">Category</td><td colspan="2">Start Date</td><td colspan="2">End Date</td><td colspan="3"></td></tr>';
        $output .= ' <tr class="field"><td class="required" colspan="3">';
        if ($subtaskObject)
            $output .= getDropDownMenuText(getSubtaskCatergoryArray(), "dropdownCategory", $subtaskObject->category);
        else
            $output .= getDropDownMenuText(getSubtaskCatergoryArray(), "dropdownCategory");
        $output .= '     *</td>';
        if ($subtaskObject) {
            $output .= commonModel::getTD(getFormInputElementText("text", "startDateTextField", '85%', getDatePickerFormat($subtaskObject->startDate), NULL, "from"), NULL, NULL, 'colspan="2"');
            $output .= commonModel::getTD(getFormInputElementText("text", "endDateTextField", '85%', getDatePickerFormat($subtaskObject->endDate), NULL, "to"), NULL, NULL, 'colspan="2"');
        } else {
            $output .= commonModel::getTD(getFormInputElementText("text", "startDateTextField", '85%', NULL, NULL, "from"), NULL, NULL, 'colspan="2"');
            $output .= commonModel::getTD(getFormInputElementText("text", "endDateTextField", '85%', NULL, NULL, "to"), NULL, NULL, 'colspan="2"');
        }
        $output .= '<td colspan = "3"></td></tr>';
//        $output .= '     <td  class="required" colspan="5">';
//        if ($subtaskObject)
//            $output .= getFormInputElementText("text", "deliverableTextField", "93%", $subtaskObject->deliverable);
//        else
//            $output .= getFormInputElementText("text", "deliverableTextField", "93%");
//        $output .= '     *</td><td colspan = "3"></td></tr>';
        //Section 3 start, end, duration, cost**************************************
        $output .= ' <tr class="row-category"><td class="col-2" colspan="10">Subtask Labor</td></tr>';
        $output .= ' <tr class ="header"><td>Type</td><td>Q1</td><td>Q2</td><td>Q3</td><td>Q4</td><td colspan="5"></td></tr>';
        $output .= ' <tr class="field">';
        $output .= '<td>Effort (Hours)</td>';
        if ($subtaskObject) {
            $output .= commonModel::getTD(getFormInputElement('text', 'q1Hours', "97%", $subtaskObject->financialObject->curYearDuration[0]));
            $output .= commonModel::getTD(getFormInputElement('text', 'q2Hours', "97%", $subtaskObject->financialObject->curYearDuration[1]));
            $output .= commonModel::getTD(getFormInputElement('text', 'q3Hours', "97%", $subtaskObject->financialObject->curYearDuration[2]));
            $output .= commonModel::getTD(getFormInputElement('text', 'q4Hours', "97%", $subtaskObject->financialObject->curYearDuration[3]));
            $output .= getHiddenField('subtaskID', $subtaskObject->ID);
            $output .= '<td colspan="5"></td>';
            $output .= ' </tr>';
        } else {
            $output .= commonModel::getTD(getFormInputElement('text', 'q1Hours', "97%"));
            $output .= commonModel::getTD(getFormInputElement('text', 'q2Hours', "97%"));
            $output .= commonModel::getTD(getFormInputElement('text', 'q3Hours', "97%"));
            $output .= commonModel::getTD(getFormInputElement('text', 'q4Hours', "97%"));
            $output .= '<td colspan="5"></td>';
            $output .= ' </tr>';
        }
        $output .= ' <tr class="field">';
        $output .= '<td>Cost ($K)</td>';
        if ($subtaskObject) {
            $output .= commonModel::getTD(getFormInputElement('text', 'q1Cost', "97%", $subtaskObject->financialObject->curYearDollars[0]));
            $output .= commonModel::getTD(getFormInputElement('text', 'q2Cost', "97%", $subtaskObject->financialObject->curYearDollars[1]));
            $output .= commonModel::getTD(getFormInputElement('text', 'q3Cost', "97%", $subtaskObject->financialObject->curYearDollars[2]));
            $output .= commonModel::getTD(getFormInputElement('text', 'q4Cost', "97%", $subtaskObject->financialObject->curYearDollars[3]));
            $output .= getHiddenField('subtaskID', $subtaskObject->ID);
            $output .= '<td colspan="5"></td>';
            $output .= ' </tr>';
        } else {
            $output .= commonModel::getTD(getFormInputElement('text', 'q1Cost', "97%"));
            $output .= commonModel::getTD(getFormInputElement('text', 'q2Cost', "97%"));
            $output .= commonModel::getTD(getFormInputElement('text', 'q3Cost', "97%"));
            $output .= commonModel::getTD(getFormInputElement('text', 'q4Cost', "97%"));
            $output .= '<td colspan="5"></td>';
            $output .= ' </tr>';
        }
        //Section 4 Dependencies****************************************************
        $output .= ' <tr class="row-category"><td class="col-2" colspan="10">Subtask Dependencies</td></tr>';
        $output .= ' <tr class ="header"><td colspan="2">Select a subtask this subtask is dependent on</td><td colspan="3">Comments</td><td colspan="5"></td></tr>';
        $output .= ' <tr class="field">';
        $output .= '     <td colspan="2">' . getDependencyDropdownText($projectID) . '</td>';
        $output .= '     <td colspan="3">' . getFormInputElementText("text", "commentsTextField", "98%", NULL, NULL, 'commentsTextField') . '</td>';
        $output .= '     <td  colspan="2">' . getFormInputElementText("button", "depAddButton", "98%", "Add Dependency", "addDependencyRow()") . '</td>';
        $output .= '     <td colspan="3"></td>';
        $output .= ' </tr>';
        $output .= '<tr>';
        $output .= '     <td class="col-2" colspan="8">' . commonModel::getDependencyTable($subtaskObject) . '</td>';
        $output .= '     <td class="col-2" colspan="2"></td>';
        $output .= ' </tr>';
        //submit button
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="6">' . getFormInputElementText("submit", "submit", NULL, "Save Subtask") . '</td>';
        $output .= '     <td colspan="4">';
        $output .= '      <input type="hidden" name="projectID" value="' . $projectID . '">';
        $output .= '      <input type="hidden" name="taskID" value="' . $taskID . '">';
        $output .= '      <input type="hidden" name="projectStartDate" value="' . $startDate . '">';
        $output .= '      <input type="hidden" name="projectEndDate" value="' . $endDate . '">';
        $output .= '     </td>';
        $output .= ' </tr>';
        $output .= getCloseTag("table");
        $output .= getCloseTag("form");
        return $output;
    }

    /**
     * Gets the dependency table for a subtask form
     * @param type $subtaskObject if not null populates the subtask fields
     * @return type an html form as a string 
     */
    static function getDependencyTable($subtaskObject) {
        $output = "";
        $output .= '  <table class="width100" cellspacing="1" id="dependencyTable">';
        $output .= '<caption>Dependency List</caption>';
        $output .= '  <col width="25%"><col width="50%"><col width="12%"><col width="13%">';
        $output .= '    <tr>';
        $output .= '      <td class ="fieldLabel">Subtask</td>';
        $output .= '      <td class ="fieldLabel">Comments</td>';
        $output .= '      <td class ="fieldLabel"></td>';
        $output .= '      <td class ="fieldLabel"></td>';
        $output .= '    </tr>';
        if ($subtaskObject && $subtaskObject->dependencies) {
            $i = 0;
            foreach ($subtaskObject->dependencies as $dependency) {
                $output .= '    <tr id="row' . $i . '">';
                $output .= '      <td class="col-2">';
                $output .= '         <input type="hidden" id="nameField' . $i . '" name="nameField' . $i . '" value="' . $dependency->subtaskId . '">' . $dependency->title . '</td>';
                $output .= '      <td class="col-2">';
                $output .= '          <input type="hidden" id="commentsField' . $i . '" name="commentsField' . $i . '" value="' . $dependency->description . '">' . $dependency->description . '</td>';
                $output .= '<td class="col-2">';
                $output .= getFormInputElement("button", $i, NULL, "Edit", "editDependencyRow(this.name)", NULL);
                $output .= '</td class ="fieldLabel">';
                $output .= '      <td class ="col-2">';
                $output .= getFormInputElement("button", $i, NULL, "Remove", "removeDependencyRow(this.name)", NULL);
                $output .= '</td>';
                $output .= '    </tr>';
                $i++;
            }
        }
        $output .= getCloseTag("table");
        return $output;
    }

    /**
     * Adds all of the subtasks cost values and sets that cost to the given task
     * @param type $taskID task cost to update
     * @param type $costType (proposedCost, approvedCost, actualCost)
     * @return type true if successful, false if failure
     */
    static function updateTaskCost($taskID, $costType) {
        //query the cost for each subtask
        $sqlSelect = "SELECT $costType FROM subtask WHERE taskID=$taskID";
        $result = executeSelect($sqlSelect);
        $taskCost = 0;
        if ($result) {
            //iterate through them and add them up
            while ($row = mysqli_fetch_assoc($result)) {
                $taskCost += $row["$costType"];
            }
            $sqlUpdate = "UPDATE task SET $costType=$taskCost WHERE taskID=$taskID";
            return executeUpdate($sqlUpdate);
        } else {
            echo 'Error finding task ' . mysqli_error() . '<br>';
            return false;
        }
    }

    /**
     * Processes the submitted create/edit subtask form
     * @return type success=redirect url, failure=NULL
     */
    static function processSubtaskSubmit() {
        //subtask stuff
        $projectID = $_POST['projectID'];
        $taskID = $_POST['taskID'];
        $subtaskTitle = $_POST['titleTextField'];
        $subtaskDescription = $_POST['descriptionTextField'];
        $category = $_POST['dropdownCategory'];
        $deliverable = $_POST['deliverableTextField'];

        //start/end
        $startDateDP = $_POST['startDateTextField'];
        $startDate = getMysqlDateFormat($startDateDP);
        $fy = getFYFromMysqlDateFormatStartDate($startDate);
        $endDateDP = $_POST['endDateTextField'];
        $endDate = getMysqlDateFormat($endDateDP);

        //labor stuff   
        $costArray = array();
        $hoursArray = array();
        $subtaskLaborCost = 0;
        $subtaskDuration = 0;
        for ($i = 1; $i < 5; $i++) {
            $cost = $_POST['q' . $i . 'Cost'];
            if (strlen($cost) == 0 || is_nan($cost))
                $cost = 0;
            $hour = $_POST['q' . $i . 'Hours'];
            if (strlen($hour) == 0 || is_nan($hour))
                $hour = 0;
            $subtaskLaborCost += $cost;
            $subtaskDuration += $hour;
            array_push($hoursArray, $hour);
            array_push($costArray, $cost);
        }
        //dependency stuff
        $dependencySubtasks = getgenericList("nameField", 20);
        $dependencyComments = getgenericList("commentsField", 20);

        //CREATE/UPDATE THE SUBTASK IN THE DATABASE        
        if (!isset($_POST['subtaskID'])) {
            //insert new wbs
            $wbsString = getWbsString(getFieldGivenAnID('task', 'taskID', $taskID, 'wbsID'));
            $nextWbs = getNextWbsAtThisLevel($wbsString);
            $wbsInsert = "INSERT into wbs (wbsString, description, other, level, fy) values ('$nextWbs', '$subtaskTitle','$subtaskDescription',3, $fy)";
            $wbsID = executeInsert($wbsInsert);
            //insert subtask
            $sqlInsert = "INSERT into subtask (taskID,title,description,duration,proposedCost,startDate,endDate, status, wbsID, category, deliverable) VALUES 
                                      ('$taskID','$subtaskTitle','$subtaskDescription','$subtaskDuration',
                                       '$subtaskLaborCost', '$startDate','$endDate', 'created', '$wbsID', '$category', '$deliverable')";
            //update the task status 
            updateStatus("active", "task", $taskID);
            $subTaskID = executeInsert($sqlInsert);
        }
        ////EDIT
        else {
            //do an update
            $subTaskID = $_POST['subtaskID'];
            $sqlUpdate = "UPDATE subtask SET title='$subtaskTitle',description='$subtaskDescription',duration='$subtaskDuration',
                                             proposedCost='$subtaskLaborCost',startDate='$startDate',
                                             endDate='$endDate', category='$category', deliverable='$deliverable' WHERE subtaskId=$subTaskID";
            executeUpdate($sqlUpdate);
        }
        //subtask creation/update success 
        if (subtaskModelClass::addDependenciesStatic($subTaskID, $dependencySubtasks, $dependencyComments)) {
            //update the proposed cost/hours
            if (subtaskModelClass::updateSubtaskFinancialsRequestManual($subTaskID, $fy, $costArray, $hoursArray)) {
                if (commonModel::updateTaskCost($taskID, "proposedCost")) {
                    //update the task POP
                    if (taskModelClass::updateTaskPOP2($taskID)) {
                        //return;
                        //update task duration
                        if (taskModelClass::updateTaskDuration($taskID)) {
                            //update project status
                            projectModelClass::updateNewProjectStatusFromOldStatic($projectID);
                            //update the project cost
                            if (!projectModelClass::updateProjectCostStatic($projectID, "proposedCost")) {
                                echo 'error updating project cost <br>';
                            } else {
                                if (isset($_POST['subtaskID']))
                                    return "location:mainPage.php?request=subtask&action=viewSubtaskDetailsRequest&subtaskId=$subTaskID&update=Subtask updated successfully";
                                else
                                    return "location:mainPage.php?request=task&action=viewTaskDetailsRequest&projectId=$projectID&taskId=$taskID&update=Subtask Created Successfully, add more below if needed";
                            }
                        } else {
                            echo 'error updating task Duration <br>';
                        }
                    } else {
                        echo 'error updating task POP <br>';
                    }
                } else {
                    echo 'error updating task cost <br>';
                }
            } else {
                echo 'Financial update failed <br>';
            }
        } else {
            echo 'error with dependencies <br>';
        }
    }

    //NOTES STUFF***************************************************************
    /**
     * We need wbsID in the post for this to be a common function
     */
    public function addNotes() {
        $notes = $_POST['textFieldNotes'];
        $personId = getPersonIDFromUsername($_SESSION['username']);
        $wbsId = $_POST['wbsID'];
        $url = $_SERVER['HTTP_REFERER'];
        $type = $_POST['notesTypeDropdown'];
        if ($this->insertNotes($notes, $type, $wbsId, $personId, $url)) {
            header("location:$url&update=Notes Added Successfully&activeDiv=notes");
        } else {
            echo "error inserting feedback <br>";
        }
    }

    /**
     * Insert notes associated with the wbsId
     * @param type $notes The text that is entered into a textfield
     * @param type $type Type of note(project, task or subtask)
     * @param type $wbsId the wbsId for the project, task or subtask getting the note
     * @param type $personId the id of the person inserting the notes
     * @param type $url What url this notes will go to if clicked
     * @param type $subtype if a subtype is needed
     * @param type $value if a value is needed (subtype required for a value)
     * @return type the sql Result of the insert (true=success false=failure)
     */
    protected function insertNotes($notes, $type, $wbsId, $personId, $url = NULL, $subtype = NULL, $value = NULL) {

        $urlLink = getUrlLink($wbsId);
        $dateCreated = date("Y-m-d");
        $lastUpdated = date("Y-m-d");
        //pin the feedback to the project and send back to project details
        if ($url) {
            if ($subtype) {
                if ($value) {
                    $sqlInsert = "INSERT into notes (type, notes, wbsId, personId, status, urlLink, dateCreated, lastUpdated, subtype, value) 
                                    values('$type','$notes', '$wbsId', $personId, 'created', '$url', '$dateCreated', '$lastUpdated', '$subtype', '$value')";
                }
                else
                    $sqlInsert = "INSERT into notes (type, notes, wbsId, personId, status, urlLink, dateCreated, lastUpdated, subtype) 
                                    values('$type','$notes', '$wbsId', $personId, 'created', '$url', '$dateCreated', '$lastUpdated', '$subtype')";
            } else {
                $sqlInsert = "INSERT into notes (type, notes, wbsId, personId, status, urlLink, dateCreated, lastUpdated) 
                                    values('$type','$notes', '$wbsId', $personId, 'created', '$url', '$dateCreated', '$lastUpdated')";
            }
        } else {
            if ($subtype) {
                if ($value) {
                    $sqlInsert = "INSERT into notes (type, notes, wbsId, personId, status, urlLink, dateCreated, lastUpdated, subtype, value) 
                                    values('$type','$notes', '$wbsId', $personId, 'created', '$urlLink', '$dateCreated', '$lastUpdated', '$subtype', '$value')";
                }
                else
                    $sqlInsert = "INSERT into notes (type, notes, wbsId, personId, status, urlLink, dateCreated, lastUpdated, subtype) 
                                    values('$type','$notes', '$wbsId', $personId, 'created', '$urlLink', '$dateCreated', '$lastUpdated', '$subtype')";
            } else {
                $sqlInsert = "INSERT into notes (type, notes, wbsId, personId, status, urlLink, dateCreated, lastUpdated) 
                                    values('$type','$notes', '$wbsId', $personId, 'created', '$urlLink', '$dateCreated', '$lastUpdated')";
            }
        }
        return executeInsert($sqlInsert);
    }

    //static functions
    /**
     * Updates the cost of a given taskID
     * @param type $taskID
     * @param type $costType (approved or proposed)
     * @return boolean
     */
    static function updateTaskCostStatic($taskID, $costType) {
        //query the cost for each subtask
        $sqlSelect = "SELECT $costType FROM subtask WHERE taskID=$taskID";
        $result = executeSelect($sqlSelect);
        $taskCost = 0;
        if ($result) {
            //iterate through them and add them up
            while ($row = mysqli_fetch_assoc($result)) {
                $taskCost += $row["$costType"];
            }
            $sqlUpdate = "UPDATE task SET $costType=$taskCost WHERE taskID=$taskID";
            return executeUpdate($sqlUpdate);
        } else {
            echo 'Error finding task ' . mysqli_error() . '<br>';
            return false;
        }
    }

    /**
     * Updated the Period of Performance of a task (called when a subtask is created, deleted or edited)
     * @param type $taskID
     * @return type
     */
    public static function updateTaskPOP2Static($taskID) {

        //get the start/end dates for all subtasks
        $sqlSelect = "SELECT st.startDate AS subtaskStart, st.endDate AS subtaskEnd 
                  FROM subtask st 
                  WHERE st.taskID=$taskID";
        $result = executeSelect($sqlSelect);

        //count rows what if someone removes the last subtask??
        if ($result && $result->num_rows > 0) {
            $row = mysqli_fetch_assoc($result);

            $minDateString = "2020-00-00";
            $maxDateString = "2000-00-00";
            $minDate = strtotime($minDateString);
            $maxDate = strtotime($maxDateString);
            //loop through each subtask and find the earliest and latest dates and set those as the task start/end dates
            do {
                $curStStartString = $row['subtaskStart'];
                $curStStart = strtotime($curStStartString);
                $curStEndString = $row['subtaskEnd'];
                $curStEnd = strtotime($curStEndString);
                if ($curStStart < $minDate) {
                    $minDate = $curStStart;
                    $minDateString = $curStStartString;
                }
                if ($curStEnd > $maxDate) {
                    $maxDate = $curStEnd;
                    $maxDateString = $curStEndString;
                }
            } while ($row = mysqli_fetch_assoc($result));

            $sqlUpdate = "UPDATE task SET startDate='$minDateString', endDate='$maxDateString' WHERE taskID=$taskID";
            return executeUpdate($sqlUpdate);
        }
        //this means this task no longer has any subtasks so let's set it back to the created state
        else {
            $sqlUpdate = "UPDATE task SET startDate='0000-00-00', endDate='0000-00-00', status='subtaskRequired' WHERE taskID=$taskID";
            return executeUpdate($sqlUpdate);
        }
    }

    /**
     * 
     * @param type $taskID
     * @return boolean
     */
    static function updateTaskDurationStatic($taskID) {
//query the cost for each subtask
        $sqlSelect = "SELECT duration FROM subtask WHERE taskID=$taskID";
        $result = executeSelect($sqlSelect);
        $taskDuration = 0;
        if ($result) {
//iterate through them and add them up
            while ($row = mysqli_fetch_assoc($result)) {
                $taskDuration += $row['duration'];
//echo $taskCost . '<br>';
            }
            $sqlUpdate = "UPDATE task SET duration=$taskDuration WHERE taskID=$taskID";
//echo $sqlUpdate . '<br>';
            return executeUpdate($sqlUpdate);
        } else {
            echo 'Error finding task ' . mysqli_error() . '<br>';
            return false;
        }
    }

    /**
     * Retrieves the header section of the financials table
     * @return string
     */
    static function getFinancialTableHeader() {
        $output = "";
        //HEADER #1-------------------------------------------------------------
        $output .= ' <tr class ="header">';
        $output .= '  <td colspan="5">Last Updated: --TO DO -- </td>';
        $output .= '  <td colspan="13" class="center">Current Year (CY)</td><td colspan="2"></td>';
        //$output .= '  <td class = "td6Center" colspan="8">Current Year Actuals</td>';
        $output .= ' </tr>';
        //HEADER #2-------------------------------------------------------------
        $output .= ' <tr class ="header">';
        $output .= '  <td colspan="3"></td>';
        $output .= '  <td colspan="2">Previous Year (PY)</td>';
        $output .= '  <td colspan="4">Milestones</td>';
        $output .= "<td></td>"; //P/A column
        $output .= '  <td colspan="4">Hours</td>';
        $output .= '  <td colspan="4">Dollars ($K)</td>';
        $output .= '  <td colspan="2">PY(s) + CY Actual</td>';
        $output .= ' </tr>';

        $output .= ' <tr class ="header">';
        $output .= '  <td colspan="3">Task/Subtask Title</td>';
        $output .= '  <td>Hours</td><td>$</td>';
        $output .= '  <td>Q1</td><td>Q2</td><td>Q3</td><td>Q4</td>';
        $output .= "<td></td>"; //P/A column
        $output .= '  <td>Q1</td><td>Q2</td><td>Q3</td><td>Q4</td>';
        $output .= '  <td>Q1</td><td>Q2</td><td>Q3</td><td>Q4</td>';
        $output .= "<td>hrs</td><td>$</td>";
        $output .= ' </tr>';
        return $output;
    }

    /**
     * Retrieves the URL that sent the last request
     * @return type
     */
    static function getUrlSource() {
        return $_SERVER['HTTP_REFERER'];
    }

    /**
     * Parses the name of a financial table field
     * @param type $pizza the name of the field
     * @return type an array of values (projectID, taskID, subtaskID, type, Quarter, real (proposed or actual), optional - rebaseline)
     */
    static function parseFinancialTableField($pizza) {
        $pieces = explode(",", $pizza);
        return $pieces;
    }

}

?>
